//Copyright (c) 2010, Goodwine & Tibia ML
//Licensed under new BSD License.

// Load options and set defaults.
function initialize() {
	options = loadOptions();
	stamina = loadStamina();
	localStorage.indicator = localStorage.indicator ? localStorage.indicator : 'icon';
	localStorage.indicator_disabled = localStorage.indicator_disabled ? localStorage.indicator_disabled : false;
	localStorage.tml = localStorage.tml ? localStorage.tml : true;
	localStorage.exh = localStorage.exh ? localStorage.exh : true;
	localStorage.psk = false;
	localStorage.opLinkPages = localStorage.opLinkPages ? localStorage.opLinkPages : JSON.stringify({'forum':true, 'guild':true, 'world':false});
}
	
function loadOptions() {
	var options;
	if (localStorage.options == null) {
		localStorage.options = '{}';
	}
	options = JSON.parse(localStorage.options);
	options.extensionEnabled = options.hasOwnProperty('extensionEnabled') ? options.extensionEnabled : true;
	options.showCaptions = options.hasOwnProperty('showCaptions') ? options.showCaptions : true;
	options.addToHistory = options.hasOwnProperty('addToHistory') ? options.addToHistory : false;
	options.displayDelay = options.hasOwnProperty('displayDelay') ? options.displayDelay : 200;
	options.fadeDuration = options.hasOwnProperty('fadeDuration') ? options.fadeDuration : 200;
	options.actionKey = options.hasOwnProperty('actionKey') ? options.actionKey : 0;
	options.disableZoomer = options.hasOwnProperty('disableZoomer') ? options.disableZoomer : false;
	localStorage.options = JSON.stringify(options);
	
	return options;
}

function loadStamina(){
	var stamina;
	if (localStorage.stamina == null) {
		localStorage.stamina = '{}';
	}
	stamina = JSON.parse(localStorage.stamina);
	stamina.h = stamina.hasOwnProperty('h') ? JSON.parse(stamina.h) : 42;
	stamina.m = stamina.hasOwnProperty('m') ? JSON.parse(stamina.m) : 0;
	stamina.premmy = stamina.hasOwnProperty('premmy') ? stamina.premmy : false;
	stamina.timeSet = stamina.hasOwnProperty('timeSet') ? stamina.timeSet : 0;
	stamina.milestone = stamina.hasOwnProperty('milestone') ? stamina.milestone : 42;	
	
	localStorage.stamina = JSON.stringify(stamina);
	return stamina;
}

// Send options to all tabs and extension pages
function sendOptions(options) {
	var request = {action: 'optionsChanged', 'options': options};
	
	// Send options to all tabs
	chrome.windows.getAll(null, function (windows) {
		for (i in windows) {
			chrome.tabs.getAllInWindow(windows[i].id, function(tabs) {
				for (j in tabs) {
					chrome.tabs.sendRequest(tabs[j].id, request);
				}
			});
		}
	});
	
	// Send options to other extension pages
	chrome.extension.sendRequest(request);
}

// Tracking code to gather statistics.
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18344881-2']);
_gaq.push(['_trackPageview']);
(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = 'https://ssl.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

function _trackOption(id, action) {
	_gaq.push(['_trackEvent', id, action]);
}

function _trackReset() {
	_gaq.push(['_trackEvent', 'Reset Defaults', 'reset']);
}

// Calculate stamina left. Considering the 10 minute lag put by Cip.
function calcStamina() {
	stamina = loadStamina();
	var hours = stamina.h;
	var mins = stamina.m;
	var oldTime = stamina.timeSet;
	var mPassed = ((new Date()).getTime() - oldTime) / (1000*60) - 10;
	if(mPassed > 0)
		if(hours < 40) {
			if(60 > mins + mPassed / 3)
				mins += mPassed / 3;
			else {
				mPassed -= (60 - mins) * 3;
				mins = 0;
				hours++;
				if(hours < 40) {
					if(hours + mPassed / 3 / 60 <= 40) {
						hours += Math.floor(mPassed / 3 / 60);
						mPassed -= Math.floor(mPassed / 3 / 60) * 60 * 3;
						if(mPassed > 0)
							if(hours < 40)
								mins = mPassed / 3;
							else
								mins = mPassed / 10;
					}
					else {
						mPassed -= (40 - hours) * 60 * 3;
						hours = 40;
						if(mPassed / 60 / 10 >= 2)
							hours = 42;
						else
						{
							hours += Math.floor(mPassed / 60 / 10);
							mPassed -= Math.floor(mPassed / 60 / 10) * 60 * 10;
							if(mPassed > 0)
								mins = mPassed / 10;
						}
					}
				}
				else {
					if(Math.floor(mPassed / 60 / 10) >= 2)
						hours = 42;
					else {
						hours += Math.floor(mPassed / 60 / 10);
						mPassed -= Math.floor(mPassed / 60 / 10) * 60 * 10;
						if(mPassed > 0)
							mins = mPassed / 10;
					}
				}
			}
		}
		else {
			if(60 > mins + mPassed / 10)
				mins += mPassed / 10;
			else {
				mPassed -= (60 - mins) * 10;
				mins = 0;
				hours++;
				if(hours + Math.floor(mPassed / 60 / 10) >= 42)
					hours = 42;
				else {
					hours += Math.floor(mPassed / 60 / 10);
					mPassed -= Math.floor(mPassed / 60 / 10) * 60 * 10;
					if(mPassed > 0)
						mins = mPassed / 10;
				}
			}
		}
	return {'hours':Math.floor(hours), 'mins':Math.floor(mins)}
}

// Saves stamina left and current time.
function saveStamina(h, m, premmy) {
	var time = /(..)(:..)/(Date());              // The prettyprinted time.
	var hour = time[1] % 24;               // The prettyprinted hour.
	var zero = time[1] < 10 ? '0' : ''; // The period of the day.
	var zeroHour = (h/10) < 1 ? '0' : '';
	var zeroMin = (m/10) < 1 ? '0' : '';
	stamina.milestone = 42;
	_trackOption('Stamina Time', h >= 42 ? 'unset' : 'set');
	_trackOption('Stamina Premmy', premmy);
	if(h >= 42) {
		var notification = webkitNotifications.createNotification(
			'../icons/48.png',                      // The image.
			zero + hour + time[2], // The title.
			'Stamina notifications have been reset.'     // The body.
		);
		notification.show();
		setTimeout(function (){ notification.cancel(); }, 5000);
	}
	else {
		var notification = webkitNotifications.createNotification(
			'../icons/48.png',                      // The image.
			zero + hour + time[2], // The title.
			'Your character has ' + zeroHour + h + 'h ' + zeroMin + m + 'm stamina left. '+
			'You will be notified when stamina is full.'     // The body.
		);
		notification.show();
		setTimeout(function (){ notification.cancel(); }, 5000);
		if(h < 14)
			stamina.milestone = 0;
		else if(h < 40)
			stamina.milestone = 14;
		else
			stamina.milestone = 40;
		stamina.h = h;
		stamina.m = m;
		stamina.timeSet =  (new Date).getTime();
		stamina.premmy = premmy;
	}
	localStorage.stamina = JSON.stringify(stamina);
}